package top.v5it.logback.push.channel.mail;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.lang.Assert;
import cn.hutool.extra.mail.GlobalMailAccount;
import cn.hutool.extra.mail.MailAccount;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Collection;
import java.util.Objects;

/**
 * 发送电子邮件请求工具
 *
 * @author zhanpu
 * @date 2021/7/25
 */
@Slf4j
public class MailUtil {

    private static final String[] MAIL_SETTING_NAMES = new String[]{"mail.setting", "mailAccount.setting"};
    private static MailAccount mailAccount;

    static {
        MailAccount account = GlobalMailAccount.INSTANCE.getAccount();
        if (Objects.nonNull(account)) {
            mailAccount = account;
        } else {
            String settingPath = System.getProperty("spring.config.location");
            Assert.notBlank(settingPath, "请设置邮箱账户");
            for (String mailSettingName : MAIL_SETTING_NAMES) {
                try {
                    mailAccount = new MailAccount(settingPath + mailSettingName);
                    break;
                } catch (IORuntimeException ignore) {
                    // ignore
                }
            }
        }
    }

    /**
     * 使用配置文件中设置的账户发送文本邮件，发送给多人
     *
     * @param tos     收件人列表
     * @param subject 标题
     * @param content 正文
     * @param files   附件列表
     * @return message-id
     */
    public static String sendText(Collection<String> tos, String subject, String content, File... files) {
        Assert.notEmpty(tos, "发送电子邮件，收件人不能为空");
        Assert.notBlank(subject, "发送电子邮件，标题不能为空");
        Assert.notBlank(content, "发送电子邮件，正文不能为空");
        String messageId = cn.hutool.extra.mail.MailUtil.send(mailAccount, tos, subject, content, false, files);
        log.trace(">>>>>Message-ID：{}", messageId);
        return messageId;
    }


    /**
     * 使用配置文件中设置的账户发送HTML邮件，发送给多人
     *
     * @param tos     收件人列表
     * @param subject 标题
     * @param content 正文
     * @param files   附件列表
     * @return message-id
     * @since 3.2.0
     */
    public static String sendHtml(Collection<String> tos, String subject, String content, File... files) {
        Assert.notEmpty(tos, "发送电子邮件，收件人不能为空");
        Assert.notBlank(subject, "发送电子邮件，标题不能为空");
        Assert.notBlank(content, "发送电子邮件，正文不能为空");
        String messageId = cn.hutool.extra.mail.MailUtil.send(mailAccount, tos, subject, content, true, files);
        log.trace(">>>>>Message-ID：{}", messageId);
        return messageId;
    }

}
